package com.hzbank.juc.introduction;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2023/12/19 - 9:17
 */
@Slf4j
public class Interrupt02 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseInterrupt twoPhaseInterrupt = new TwoPhaseInterrupt();
        twoPhaseInterrupt.start();
        TimeUnit.SECONDS.sleep(10);
        twoPhaseInterrupt.stop();
    }
    static class TwoPhaseInterrupt {
        private Thread thread;
        public void start() {
            thread = new Thread(() -> {
                while (true) {
                    Thread currentThread = Thread.currentThread();
                    if (currentThread.isInterrupted()) {
                        log.debug("线程被打断，线程之父可以过来料理后事了");
                        break;
                    }
                    try {
                        log.debug("健康着呢");
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        currentThread.interrupt();
                    }
                }
            });
            thread.start();
        }
        public void stop() {
            thread.interrupt();
        }
    }
}
